package com.qs.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.URLUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.apistd.uni.Uni;
import com.apistd.uni.UniException;
import com.apistd.uni.UniResponse;
import com.apistd.uni.sms.UniMessage;
import com.apistd.uni.sms.UniSMS;
import com.qs.annotation.OperationLog;
import com.qs.config.ossconfig.OSSClient;
import com.qs.constant.RedisConstant;
import com.qs.response.Response;
import com.qs.utils.RandomNumberUtils;
import lombok.RequiredArgsConstructor;
import lombok.experimental.PackagePrivate;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * ClassName: UploadContrller
 * Package: com.qs.controller
 * Description:
 *
 * @Author: @weixueshi
 * @Create: 2023/11/11 - 15:38
 * @Version: v1.0
 */
@Slf4j
@CrossOrigin
@RestController
@RequestMapping("/common")
@RequiredArgsConstructor
public class CommonController {

    private final RedisTemplate redisTemplate;

    @Value("${uni.sms.key}")
    public String ACCESS_KEY_ID;

    /**
     * 头像上传接口
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public Response upload(@RequestParam("file") MultipartFile file){
        try {
            // 创建OSS实例
            OSS ossClient = new OSSClientBuilder().build(OSSClient.ENDPOINT, OSSClient.ACCESS_KEY, OSSClient.SECRET_KEY);
            log.info("文件开始上传...");
            // 获取文件原始名称
            String filename = file.getOriginalFilename();
            // 完善1、 --> 在文件名中添加唯一值
            String uuid = UUID.randomUUID().toString().replace("-", "");
            filename = uuid + filename;
            // 完善2、 --> 把文件按照日期分类
            String datePath = new DateTime().toString("yyyy/MM/dd");
            // 拼接时间 yyyy/MM/dd/filename
            filename = datePath + "/" + filename;
            ossClient.putObject(OSSClient.BUCKET_NAME, filename, file.getInputStream());
            log.info("文件上传成功...");
            String avatarUrl = "https://"+ OSSClient.BUCKET_NAME +"."+OSSClient.ENDPOINT+"/"+filename;
            return Response.success(avatarUrl);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 富文本图片上传接口
     * @param file
     * @return
     */
    @PostMapping("/editor/upload")
    public Dict editorUpload(@RequestParam("file") MultipartFile file){
        try {
            // 创建OSS实例
            OSS ossClient = new OSSClientBuilder().build(OSSClient.ENDPOINT, OSSClient.ACCESS_KEY, OSSClient.SECRET_KEY);
            log.info("文件开始上传...");
            // 获取文件原始名称
            String filename = file.getOriginalFilename();
            // 完善1、 --> 在文件名中添加唯一值
            String uuid = UUID.randomUUID().toString().replace("-", "");
            filename = uuid + filename;
            // 完善2、 --> 把文件按照日期分类
            String datePath = new DateTime().toString("yyyy/MM/dd");
            // 拼接时间 yyyy/MM/dd/filename
            filename = datePath + "/" + filename;
            ossClient.putObject(OSSClient.BUCKET_NAME, filename, file.getInputStream());
            log.info("文件上传成功...");
            String avatarUrl = "https://"+ OSSClient.BUCKET_NAME +"."+OSSClient.ENDPOINT+"/"+filename;
            /**
             * {
             *     "errno": 0, // 注意：值是数字，不能是字符串
             *     "data": {
             *         "url": "xxx", // 图片 src ，必须
             *         "alt": "yyy", // 图片描述文字，非必须
             *         "href": "zzz" // 图片的链接，非必须
             *     }
             * }
             */
            Dict dict = Dict.create().set("errno",0).set("data", CollUtil.newArrayList(Dict.create().set("url", avatarUrl)));
            return dict;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 短信发送接口
     * @param phone
     * @return
     */
    @PostMapping("/sendMs/{phone}")
    public Response sendMs(@PathVariable("phone") String phone) {
        // 初始化
        // 若使用简易验签模式仅传入第一个参数即可
        Uni.init(ACCESS_KEY_ID);
        // 设置自定义参数 (变量短信)
        Map<String, String> templateData = new HashMap<String, String>();
        //生成随机数
        String code = RandomNumberUtils.generateRandomNumber();
        templateData.put("code", code);
        templateData.put("ttl", "2");
        // 构建信息
        //TODO: 注意：setSignature()方法的参数配置成自己的短信签名名称
        UniMessage message = UniSMS.buildMessage()
                .setTo(phone)
                .setSignature("石文学测试")
                .setTemplateId("pub_verif_register_ttl")
                .setTemplateData(templateData);
        // 发送短信
        try {
            UniResponse res = message.send();
            //将验证码进行缓存，设置两分钟的缓存时间
            redisTemplate.opsForValue().set(RedisConstant.MESSAGE_CODE + phone,code,3, TimeUnit.MINUTES);
            log.info("短信发送成功！{}",res);
            return Response.success();
        } catch (UniException e) {
            System.out.println("Error: " + e);
            System.out.println("RequestId: " + e.requestId);
        }
        return null;
    }
}
